//
//  HKAvVideoRecorder.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/20.
//

#import "HKAvVideoRecorder.h"
#import <AVFoundation/AVFoundation.h>
#import "SimpleAudioPlayer.h"
#import "HKLoadingView.h"
#import "HTTPURL.h"
#import "HKUser.h"
#import "HKCommonDefine.h"
#import "HKRequestDefine.h"

@interface HKAvVideoRecorder () <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioRecorder *audioRecorder;
@property (nonatomic, strong) AVAudioPlayer *avPlayer;
@property (nonatomic, strong) AVAudioSession *session;

@end

@implementation HKAvVideoRecorder

- (instancetype)init {
    if (self = [super init]) {
        [self setupSessionWithCategroy:AVAudioSessionCategoryPlayAndRecord];
    }
    return self;
}

- (void)createRecord {
    if (!self.audioRecorder) {
        NSError *error;
        NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
        
        if (@available(iOS 11.0, *)) {
            [recordSetting setObject:@(kAudioFileWAVEType) forKey:AVAudioFileTypeKey];
        } else {
            // Fallback on earlier versions
        }

        [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
        [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
        
        //        @{AVNumberOfChannelsKey:@1,
        //                                                                                                          AVFormatIDKey:@(kAudioFormatLinearPCM),       AVLinearPCMBitDepthKey:@(8),
        //                                                                                                          AVLinearPCMIsFloatKey: @(YES),                                                      AVSampleRateKey:@44100,
        //                                                      AVEncoderAudioQualityKey:@(AVAudioQualityMax),
        //                                                                                                          AVEncoderBitDepthHintKey: @16}
        self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:[self filePathUrl] settings:recordSetting.copy error:&error];
        self.audioRecorder.delegate = self;
        self.audioRecorder.meteringEnabled = YES;
        [self.audioRecorder prepareToRecord];
    }
}

- (void)startRecord {
    [self setupSessionWithCategroy:AVAudioSessionCategoryRecord];
    [self createRecord];
    if (!self.audioRecorder.isRecording) {
        BOOL isRecord = [self.audioRecorder record];
        NSLog(@"hzk %@",@(isRecord));
    }
}

- (void)playRecord {
    if (!self.audioRecorder.isRecording) {
        [self.audioRecorder record];
    }
}

- (void)pauseRecord {
    [self.audioRecorder pause];
}

- (void)stopRecord {
    [self.audioRecorder stop];
    if (self.toHasFinishRecordBlock) {
        self.toHasFinishRecordBlock();
    }
}

- (void)playAv {
    [self setupSessionWithCategroy:AVAudioSessionCategoryPlayback];
    NSError *error;
    NSURL *fileUrl = [self filePathUrl];
    if (!fileUrl) return;
    self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    [self.avPlayer setNumberOfLoops:0];
    [self.avPlayer setVolume:0.9];
    [self.avPlayer setDelegate:self];
    [self.avPlayer play];
}

- (void)setupSessionWithCategroy: (NSString *)categoryConstant {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    BOOL success = [audioSession setCategory:categoryConstant error:&setCategoryError];
    if (!success) { /* handle the error condition */ }
    
    NSError *activationError = nil;
    success = [audioSession setActive:YES error:&activationError];
    
    // todo - handle error
    if (!success) { /* handle the error condition */ }
}

- (void)stopAV {
    [self.avPlayer stop];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
}

/* if an error occurs while decoding it will be reported to the delegate. */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error {
    
}

- (NSURL *)filePathUrl {
    // sets the path for audio file
    NSArray *pathComponents = [NSArray arrayWithObjects:
                               [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
                               @"voice.caf",
                               nil];
    NSURL *fileUrl = [NSURL fileURLWithPathComponents:pathComponents];
    return fileUrl;
}

#pragma mark - delegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
}

/* if an error occurs while encoding it will be reported to the delegate. */
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error {
    
}

@end
